import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { User } from '../../database/schemas/user.schema';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { UserDto } from '../users/user.dto';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UsersService,
    private readonly jwtService: JwtService
  ) {}

  async signIn(user: User) {
    const token = this.jwtService.sign(user);
    return {
      token,
      user
    };
  }

  async validateUser(username: string, password: string): Promise<User | null> {
    const user = await this.userService.findByName(username);

    if (user && bcrypt.compareSync(password, user.password)) {
      delete user.password;
      return user;
    }
    return null;
  }

  async signUp(newUser: UserDto): Promise<User> {
    const user = await this.userService.findByName(newUser.username);
    if (user) {
      throw new HttpException('username existed', HttpStatus.FORBIDDEN);
    }
    return this.userService.save({
      ...newUser,
      password: bcrypt.hashSync(newUser.password, 10)
    });
  }
}
